<template>
	<view class="content">
		<view class="wrap">
			<swiper class="swiper" circular :indicator-dots="carouselImage.length>1" :autoplay="autoplay">
				<swiper-item v-for="(i,index) in carouselImage" :key="i.image">
					<image lazy-load :lazy-load-margin="0" style="width: 100%; height: 240rpx;" mode="scaleToFill"
						:src="`${app.imgUrl}${i.image}`" @click="callPhone(i,index)"></image>
				</swiper-item>
			</swiper>
		</view>
		<view class="main">
			<view class="menu cardBorder">
				<uni-grid :column="4" @change="changeMenuItem" :show-border="false">
					<uni-grid-item v-for="(item, index) in menus" :index="index" :key="item.id">
						<button class="grid-item-box" open-type="contact" v-if="item.name=='询价下单'">
							<image class="image" :src="`${app.imgUrl}${item.image}`" mode="aspectFill" />
							<text class="text">{{item.name}}</text>
						</button>
						<view v-else class="grid-item-box">
							<image class="image" :src="`${app.imgUrl}${item.image}`" mode="aspectFill" />
							<text class="text">{{item.name}}</text>
						</view>
					</uni-grid-item>
				</uni-grid>
			</view>
			<view class="line cardBorder">
				<view class="tab">
					<view class="tab-item" :class="{'tab-cur':currentIndex===index}" @click="onClickItem(index)"
						v-for="(i,index) in tabArr" :key="index">
						{{i}}
					</view>
				</view>
				<view class="select">
					<view class="select-title">
						价格(单位：元)
					</view>
					<view class="select-comp">
						<div class="select-comp-text">规格：</div>
						<uni-data-select class="uniSelect" @change="changeSlecte" :clear="false" v-model="selectValue"
							style="width: 200rpx;" :localdata="range"></uni-data-select>
					</view>
				</view>
				<view class="price">
					<qiun-data-charts v-if="chartData" type="line" :opts="opts" :chartData="chartData" :ontouch="true"
						:canvas2d="true" canvasId="KLJRpvOkalbfJEFEEwbjnuZppaITnFyx" />
					<view v-else="!chartData" class="price-empty">
						暂无数据
					</view>
				</view>
			</view>
			<view class="bottom cardBorder" v-if="bottomImage">
				<image class="bottom-image" lazy-load mode="widthFix" :src="`${app.imgUrl}${bottomImage}`"></image>
			</view>
		</view>
		<uni-popup ref="popup" :mask-click="true" background-color="#fff" borderRadius="20px 20px 0 0">
			<view class="popupbg">
				<view class="popupbg-title">
					欢迎来到钢价通
				</view>
				<view class="popupbg-title2">
					查看价格详情信息
				</view>
				<button class="popupbg-login" open-type="getPhoneNumber" @getphonenumber="getUserPhoneNumber">
					一键登录
				</button>
				<view class="popupbg-close">
					<label class="radio">
						<radio style="transform:scale(0.8)" @click="isSelect=!isSelect" :checked="isSelect" />
					</label>
					<span class="bot_text">登录表示已阅读同意《<span @click="jumpAgreement" class="agreement">用户协议</span>》</span>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		toRefs
	} from 'vue'
	import {
		onLoad,
		onReachBottom,
		onShareAppMessage,
		onShareTimeline,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import tool from "../../utils/common.js"
	import {
		usePhoneStore
	} from '../../store/index.js'
	const Phone = usePhoneStore()
	const app = getApp().globalData.utils
	const swiperRef = ref(null);
	const popup = ref();
	const data = reactive({
		menus: [],
		carouselImage: [],
		specifications: [],
		autoplay: true,
		tabArr: ["近一周", "近一月", "近一年"],
		bottomImage: null,
		chartData: null,
		currentIndex: 0,
		selectValue: "",
		range: [],
		isLogin: false,
		openid: '',
		sessionKey: '',
		authCode: '',
		isSelect: false,
		opts: {
			color: ["#EE6666"],
			padding: [10, 15, 5, 10],
			dataLabel: false,
			dataPointShape: false,
			enableScroll: true,
			legend: {
				show: false
			},
			xAxis: {
				disableGrid: false,
				gridColor: "#ddd",
				boundaryGap: "justify",
				axisLineColor: "#ddd",
				scrollShow: true,
				scrollAlign: "right",
				fontColor: "#777",
				itemCount: 8,
				fontSize: 12,
				formatter: (value, index) => {
					return value ? value.slice(5, 10) : value
				}
			},
			yAxis: {
				gridType: "solid",
				gridColor: "#ddd",
				data: [{
					axisLineColor: "#ddd",
					fontSize: 12,
					fontColor: "#777",
				}]
			},
			extra: {
				tooltip: {
					bgColor: "#000",
					showArrow: false,
					bgOpacity: 0.4,
					borderRadius: 5,
					fontColor: "#fff",
					legendShow: false,
					legendShape: "circle",
					gridType: "dash",
					gridColor: "#bababa",
					dashLength: 6,
				},
				line: {
					type: "curve",
					width: 1,
					activeType: "hollow",
					linearType: "custom"
				}
			}
		}
	})

	const {
		menus,
		carouselImage,
		specifications,
		autoplay,
		tabArr,
		currentIndex,
		range,
		selectValue,
		bottomImage,
		chartData,
		opts,
		openid,
		authCode,
		isLogin,
		sessionKey,
		isSelect
	} = toRefs(data)
	onLoad(async () => {
		console.log(Phone)
		await login()
		await getHomeData()
		await getLineChart(currentIndex.value + 1, selectValue.value)
	})
	onReachBottom(() => {})

	onPullDownRefresh(async () => {
		// 实现数据更新的逻辑
		await getHomeData()
		await getLineChart(currentIndex.value + 1, selectValue.value)
	})
	/* 跳转协议 */
	const jumpAgreement = () => {
		uni.navigateTo({
			url: '../agreement/user'
		});
	}
	/* 点击一键拨号 
		effect 0:静态;1:弹出手机号;2:弹出二维码;3:跳转
	*/
	const callPhone = (val, index) => {
		switch (val.effect) {
			case 0:
				break;
			case 1:
				tool.callPhone(val.effectContent)
				break;
			case 2:
				uni.navigateTo({
					url: `addv?addvData=${JSON.stringify(val)}`
				});
				break;
		}
	}
	/* 点击菜单 */
	const changeMenuItem = async (item) => {

		let menuItem = menus.value[item.detail.index]
		if (menuItem.name === "询价下单") return
		if (menuItem.name === "询价下单" || menuItem.name === "售后服务") {
			console.log(Phone.salePhone)
			tool.callPhone(Phone.salePhone)
			return
		}
		if (menuItem.name === "物流信息") {
			return uni.navigateTo({
				url: '../logistics/index'
			});
		}
		if (menuItem.type === 2) {
			return uni.hideLoading({
				complete: () => {
					uni.showToast({
						title: '该服务暂未开放',
						icon: 'none',
					})
				}
			})
		}

		isLogin.value = uni.getStorageSync('openId') ? true : false
		if (!isLogin.value) {
			const res = await app.getExistCode({
				code: authCode.value
			});
			if (res&&res.openId) {
				sessionKey.value = res.sessionKey
				openid.value = res.openId
				console.log(res)
				if (!res.isLogined) {
					return popup.value.open('bottom')
				}else{
					uni.setStorageSync('openId', openid.value)
				}
			} 
		}
		uni.navigateTo({
			url: `detail?menuData=${JSON.stringify(menuItem)}`
		});

	}
	/* 登录 */
	const login = () => {
		// const accountInfo = uni.getAccountInfoSync()
		uni.login({
			// onlyAuthorize: true,
			provider: 'weixin',
			success: function(loginRes) {
				authCode.value = loginRes.code;
				console.log('loginRes', loginRes.code)
			}
		});
	}
	/* 获取手机号 */
	const getUserPhoneNumber = async (e) => {
		isSelect.value = true
		if (e.detail.errMsg == "getPhoneNumber:ok") {
			const encryptedData = e.detail.encryptedData;
			const iv = e.detail.iv;
			// 将encryptedData、iv发送到服务器进行解密获取手机号
			// const phoneNumber = res.data.phoneNumber;
			let params = {
				openId: openid.value,
				encryptedData: encryptedData,
				iv: iv,
				sessionKey: sessionKey.value
			}
			// 此处可以将手机号存储起来，或者进行其他操作
			let resPhone = await app.postVisitPhone(params)
			console.log(resPhone)
			if (resPhone) {
				uni.setStorageSync('openId', openid.value)
				uni.hideLoading({
					complete: () => {
						uni.showToast({
							title: '登录成功',
							icon: 'none',
						})
					}
				})
				popup.value.close()
			} else {
				return uni.hideLoading({
					complete: () => {
						uni.showToast({
							title: '服务器繁忙，请稍后再试',
							icon: 'none',
						})
					}
				})
			}
		} else {
			console.log('用户拒绝授权');
		}
	}
	/* 点击切换折现图tab */
	const onClickItem = (e) => {
		if (currentIndex.value === e) return
		currentIndex.value = e
		getLineChart(currentIndex.value + 1, selectValue.value)
	}
	/* 下拉框选择 */
	const changeSlecte = () => {
		chartData.value = null
		getLineChart(currentIndex.value + 1, selectValue.value)
	}
	/* 获取首页数据 */
	const getHomeData = async () => {
		const res = await app.getHomeData()
		console.log('首页数据', res)
		Phone.setSalePhoneObj(res.phone)
		carouselImage.value = res.carouselImage
		menus.value = res.menus
		bottomImage.value = res.bottomImage
		if (res.specifications.length > 0) {
			specifications.value = res.specifications
			selectValue.value = res.specifications[0]
			let arr = []
			for (let item in res.specifications) {
				let obj = {
					value: res.specifications[item],
					text: res.specifications[item]
				}
				arr.push(obj)
			}
			range.value = arr
		}
	}
	/* 获取折现图数据 */
	const getLineChart = async (dateRange, spcification) => {
		const params = {
			dateRange: dateRange,
			spcification: spcification
		}
		const res = await app.getHomePriceCurve(params)
		let seriesData = []
		let categoriesData = []

		if (res && Object.keys(res).length !== 0) {
			for (let s in res) {
				seriesData.push(res[s])
				let dateWord = s.slice(0, 10)
				categoriesData.push(dateWord.replace(/-/g, "/"))
			}
			opts.value.xAxis.scrollShow = categoriesData.length > 8
			let options = {
				categories: categoriesData,
				series: [{
					name: "价格",
					data: seriesData
				}]
			};
			chartData.value = JSON.parse(JSON.stringify(options))
		} else {
			chartData.value = null
		}

	}
	onShareAppMessage((res) => { //发送给朋友
		return {
			title: '钢价通',
			path: 'pages/home/index',
		}
	})
	onShareTimeline((res) => { //分享到朋友圈
		return {
			title: '钢价通',
			path: 'pages/home/index',
		}
	})
</script>

<style lang="scss" scoped>
	.content {
		width: 100vw;
		height: 100%;
		min-height: 100vh;
		background-color: #eee;
	}

	.cardBorder {
		box-sizing: border-box;
		border-radius: 20rpx;
		overflow: hidden;
		margin-top: 30rpx;
		background-color: #fff;
	}

	.wrap {
		width: 100%;
		height: 240rpx;
	}

	.swiper {
		height: 240rpx;
		z-index: 999;
	}

	.swiper-item {
		display: block;
		height: 240rpx;
		line-height: 240rpx;
		text-align: center;
	}

	.swiper-list {
		margin-top: 40rpx;
		margin-bottom: 0;
	}

	.main {
		padding: 0 30rpx 30rpx;
		width: 100%;
		box-sizing: border-box;
	}

	.menu {
		button {
			background: none;
			/* 去除背景样式 */
			border: none;
			/* 去除边框样式 */
			box-shadow: none;
			/* 去除阴影样式 */
			color: inherit;
			/* 文字颜色继承父元素 */
			font: inherit;
			/* 字体样式继承父元素 */
			outline: none;
			/* 去除点击后的轮廓线 */
			padding: none;
			/* 去除内边距 */
			border-radius: 0;
		}

		button::after {
			border: none;
		}

		.grid-item-box {
			flex: 1;
			// position: relative;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 0rpx 0;

			.image {
				width: 85rpx;
				height: 85rpx;
				border-radius: 50%;
			}

			.text {
				font-size: 24rpx;
				margin-top: 16rpx;
				color: #000;
			}
		}
	}

	.tab {
		width: 100%;
		height: 75rpx;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		font-size: 26rpx;

		&-item {
			flex: 1;
			height: 71rpx;
			line-height: 71rpx;
			text-align: center;
			background-color: #fff;
			color: #cd4541;
			border: 2rpx solid #cd4541;
		}

		&-cur {
			color: #fff;
			background-color: #cd4541;
		}

		:last-child {
			border-left: none;
			border-radius: 0 20rpx 0 0;
		}

		:first-child {
			border-radius: 20rpx 0 0 0;
			border-right: none;
		}

		&-item:active {
			opacity: 0.7;
		}
	}

	.select {
		font-size: 13px;
		margin-top: 20rpx;
		padding: 0 10rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		&-comp {
			width: 300rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}

		::v-deep .uniSelect {
			.uni-select__selector-scroll {
				max-height: 240rpx;
			}
		}
	}

	.price {
		margin-top: 0rpx;
		box-sizing: border-box;
		padding: 0 20rpx 20rpx;
		width: 100%;
		height: 350rpx;
		display: show;

		&-empty {
			font-size: 24rpx;
			color: #8a8a8a;
			text-align: center;
			line-height: 350rpx;
		}
	}

	.bottom {
		width: 100%;

		&-image {
			width: 100%;
		}
	}

	.popupbg {
		height: 320rpx;
		background-color: #fff;
		border-radius: 40rpx 40rpx 0 0;
		padding: 30rpx;

		&-title {
			font-size: 36rpx;
			color: #000;
			font-weight: 600;
			margin: 20rpx 0 10rpx;
		}

		&-title2 {
			font-size: 24rpx;
			color: #a7a7a7;
		}

		&-login {
			width: 100%;
			height: 100rpx;
			background-color: #cd4541;
			color: #fff;
			text-align: center;
			line-height: 100rpx;
			border-radius: 100rpx;
			font-size: 32rpx;
			margin: 30rpx 0 20rpx;
		}

		&-close {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			font-size: 26rpx;

			.bot_text {
				color: #7c7c7c;
			}

			.agreement {
				color: #cd4541;
			}
		}
	}
</style>